package map;

import java.awt.Checkbox;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Robot;

public class Util {
    private MapColor mapColor;//保存填充颜色的对象
    private Polygon[] polArray;//保存多边形的数组
    private Checkbox checkbox;
    private int current = 0;
    int[][] metrix;

    /**
     * 构造函数
     * */
    public Util(MapColor mapColor, Polygon[] polArray, Checkbox checkbox, int[][] metrix) {
        this.mapColor = mapColor;
        this.polArray = polArray;
        this.checkbox = checkbox;
        this.metrix = metrix;
    }

    /**
     * 检查当前省颜色是否合法
     * @param province 省份颜色数组
     * */
    public boolean isOK(int province[]) {
        for(int j=0;j<current;j++)
            if(metrix[current][j]==1&&province[j]==province[current])
                return false;
        return true;
    }

    /**
     * 为所有省上色
     * @param province 省份颜色数组
     * */
    public int color(int province[]) {
        int i = 0;
        if(current<=33)
            for(i=0;i<4;i++)
            {
                province[current]=i;
                Graphics g = mapColor.getGraphics();
                mapColor.fillColor(g, current, i);
                if(checkbox.getState())
                    try{
                        Robot r = new Robot();
                        r.delay(150);
                    }
                    catch(Exception e){}
                if(isOK(province)){
                    current++;
                    int j = color(province);
                    if(j==-1){
                        current--;
                        province[current]=-1;
                    }
                    if(current>33) return 1;
                }
            }
        if(i>=4) return -1;
        return 1;
    }

    /**
     * 回溯
     * */
    public void backtrack(){
        int province[]=new int[34];
        color(province);
    }

    /**
     * 重置地图
     * */
    public void resetMap(){
        Graphics g = mapColor.getGraphics();
        for(int k=0;k<34;k++){
            mapColor.fillColor(g, k, 4);
        }
        mapColor.paint(g);
    }
}
